package com.zhangln.mountbuzhou.listener;

import com.rabbitmq.client.Channel;
import com.zhangln.mountbuzhou.dto.BaseResponse;
import com.zhangln.mountbuzhou.dto.request.PushMsgReq;
import com.zhangln.mountbuzhou.service.PushService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.io.ObjectInputStream;

/**
 * @author sherry
 * @description
 * @date Create in 2020/4/28
 * @modified By:
 */
@Slf4j
@Component
public class PushMsgListener {

    private final PushService pushService;

    public PushMsgListener(PushService pushService) {
        this.pushService = pushService;
    }

    @RabbitListener(queues = "#{webSocketPushAnonymousQueue.name}")
    public void pushMsgProcess(Message message, Channel channel) {
        log.info("监听到日志请求");
        byte[] body = message.getBody();
        try (ByteArrayInputStream bais = new ByteArrayInputStream(body);
             ObjectInputStream oii = new ObjectInputStream(bais)) {
            Object o = oii.readObject();
            //再做一次强制类型转化，就可以拿到生产者发送的对象数据了
            PushMsgReq pushMsgReq = (PushMsgReq) o;
            BaseResponse baseResponse = pushService.pushMsg(pushMsgReq);
            log.info(String.valueOf(baseResponse));
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        } finally {
            try {
                // 返回确认状态
                channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            } catch (Exception e) {
                log.error("RabbitMQ 网关日志ACK异常", e);
            }
        }
    }

}
